<template>
    <!-- Main content -->
    <div>
        <div class="row">
            <div class="col-xs-12">
                <theme-box title="广告列表">
                    <form class="form-inline" @submit.prevent v-el:form>
                        <form-select title="类型" :sreach="true" :up-table="true" :options="typeOptions"
                                     name="linkType"></form-select>
                        <form-select title="状态" :sreach="true" :up-table="true" :options="stateOptions"
                                     name="state"></form-select>

                        <button type="reset" @click="reset" class="btn btn-warning pull-right">重置</button>
                        <v-button theme="primary" @click="search" class="pull-right">查询</v-button>
                    </form>
                    <table class="table table-bordered table-striped" style="width:100%" v-el:table>
                    </table>
                </theme-box>
            </div>
            <!-- /.col -->
        </div>
        <modal-container title="修改" v-el:revise-modal v-ref:revise-modal class="edit-modal" theme="big">
            <form @submit.prevent @reset.prevent v-el:revise-mform>
                <div class="modal-body">
                    <table-modal :item="item" :columns-set="columnsReviseSet" v-ref:item></table-modal>
                </div>

                <div class="modal-footer">
                    <v-button class="pull--left" data-dismiss="modal" @click="resetBindDrag">关闭</v-button>
                    <v-button theme="primary" type="submit">保存</v-button>
                </div>
            </form>

        </modal-container>
        <!-- /.row -->
    </div>
    <!-- /.content -->
</template>

<style lang="less" scoped>
    .form-inline .btn + .btn {
        margin-right: 10px;
    }

    .form-inline .form-group + .form-group {
        margin-left: 20px;
    }
</style>
<script>
    import {
        dateTime,
        createDataTable
    } from 'ui/collections/general.js'
    var serialize = require('form-serialize');
    import {dateFormat} from "lib/method.js"

    var dataTable;
    var columnsSet;
    export default {
        data: () => ({
            item: {},
            columnsSet: [],
            linkDocId:[],
            typeOptions: [
                {key: "所有类型", value: ""},
                {key: "默认", value: "normal"},
                {key: "外部链接", value: "url"},
                {key: "内部链接", value: "inner"},
                {key: "发现", value: "find"},
                {key: "商户", value: "mcht"}
            ],
            stateOptions: [
                {key: "所有状态", value: ""},
                {key: "正常", value: "0"},
                {key: "关闭", value: "1"}
            ],
            columnsReviseSet: [{
                title: "广告号",
                data: "banId",
                edit: true,
                readonly: true,
                className: "operate"
            }, {
                title: "名称",
                data: "name",
                edit: true,
                className: "operate"
            }, {
                title: "图片",
                data: "picUrl",
                img: true,
                upload: true,
                className: "operate",
                render: function (data) {
                    return `<img class="table-avatar" src=` + data + `>`
                }
            }, {
                title: "简介",
                data: "about",
                edit: true,
                className: "operate"
            }, {
                title: "关联类型",
                data: "linkType",
                options: [{key: "默认", value: "normal"}, {key: "外部链接", value: "url"},{key: "内部链接", value: "inner"},{key: "发现", value: "find"},{key: "商户", value: "mcht"}],
                className: "operate"
            }, {
                title: "关联URL",
                data: "linkUrl",
                edit: true,
                readonly: false,
                className: "operate",
                render(data, type, row){
                    if (row.linkType == "normal") {
                        return ""
                    } else {
                        return data
                    }
                }
            }, {
                title: "关联文章",
                data: "linkDocId",
                readonly: false,
                className: "operate"
            }, {
                title: "关联商户",
                data: "linkMchtId",
                readonly: false,
                className: "operate"
            }, {
                title: "顺序",
                data: "seq",
                edit: true,
                className: "operate"
            }
            ]

        }),
        methods: {
            //还原弹出框位置
            resetBindDrag() {
                this.$refs.reviseModal._resetBindDrag();
            },
            //查询按钮
            search: function () {
                dataTable.ajax.reload();
            },
            //重置按钮
            reset: function () {
                $(".form-inline")[0].reset();
                dataTable.ajax.reload();
            }
        },
        created() {
            //datatable所用数组
            columnsSet = [{
                title: "广告号",
                data: "banId",
                edit: true,
                className: "operate"
            }, {
                title: "名称",
                data: "name",
                edit: true,
                className: "operate",
                className:'wrap'
            }, {
                title: "简介",
                data: "about",
                edit: true,
                className: "operate",
                className:'wrap'
            }, {
                title: "图片",
                data: "picUrl",
                img: true,
                className: "operate",
                render: function (data) {
                    return `<img class="table-avatar" src=` + data + `>`
                }
            }, {
                title: "关联类型",
                data: "linkType",
                className: "operate",
                render: function (data) {
                    if(data == "normal"){
                        return "默认";
                    }else if (data == "url"){
                        return "外部链接";
                    }else if (data == "inner"){
                        return "内部链接";
                    }else if(data == 'find'){
                        return "发现";
                    }else{
                        return "商户"
                    }
                }
            }, {
                title: "关联文章",
                data: "linkDocId",
                className: "operate"
            }, {
                title: "状态",
                data: "state",
                options: [{key: "开启", value: "0"}, {key: "关闭", value: "1"}],
                className: "operate",
                render: function (data) {
                    return (data == "0") ? "开启" : "关闭"
                }
            }, {
                title: "顺序",
                data: "seq",
                edit: true,
                className: "operate"
            }, {
                title: "最后修改时间",
                data: "lastTime",
                datetime: true,
                className: "operate",
                render: function (data) {
                    return dateFormat(data)
                }
            }, {
                title: "相关操作",
                className: "operate",
                width: "160px",
                render: function (value, type, row) {
                    if (row.state == "1") {
                        return `
                            <button type="button" class="btn btn-primary btn-sm revise">修改</button>
                            <button type="button" class="btn btn-danger btn-sm delete">删除</button>
                            <button type="button" class="btn btn-danger btn-sm state">开启</button>
                        `
                    } else {
                        return `
                        <button type="button" class="btn btn-danger btn-sm state">关闭</button>
                        `
                    }
                }
            }]
        },
        ready: async function () {
            $(".dataTable img").css({"width": "50px", "height": "50px"});
            dateTime({
                format: "yyyy-mm-dd",
                minView: "2"
            })
            var linkTpeWatch = function () {
            };
            this.$set("columnsSet", columnsSet)
            var self = this;
            dataTable = $(this.$els.table).DataTable({
                "columns": this.columnsSet, //定义列
                "ajax": async function (data, callback, settings) {
                    var page = [{
                        "name": "iDisplayStart",
                        "value": 1 + data.start / data.length
                    }, {
                        "name": "iDisplayLength",
                        "value": data.length
                    }];
                    //表单序列化数据
                    var _data = serialize(self.$els.form, {
                        hash: true,
                        disabled: true,
                        empty: true
                    });
                    _data.aoData = JSON.stringify(page);
                    //发送请求
                    var result = await self.$post({
                        url: "/api/v1" + projectName_Url + "/plat/banner/query",
                        data: _data,
                        method: "POST"
                    })
                    if (result.respCode != "00") {
                        Midway.alert({
                            title: "操作失败",
                            content: result.content
                        })
                    }
                    callback({
                        recordsTotal: result.content.total,
                        recordsFiltered: result.content.total,
                        data: result.content.list || []
                    })
                }
            });

            $(self.$el).on("click", ".revise", function () {
                var Row = $(this).closest('tr').get(0);
                const dataArray = JSON.parse(JSON.stringify(dataTable.row(Row).data()));
                self.item = dataArray;

                if(self.item.linkDocId == null || self.item.linkDocId == ''){
                    self.$post({
                        url: "/api/v1" + projectName_Url + "/list/doc/query/0",
                        method: "GET"
                    }).then(response => {
                        let _array = [];
                        if(response.content.info != null){
                            for(let i=0;i<response.content.info.length;i++){
                                _array.push({value:response.content.info[i].value,key:response.content.info[i].key});
                            }
                        }
                        self.$set("columnsReviseSet[6].options",_array)
                    }, error => {
                    });
                }else{
                    self.$post({
                        url: "/api/v1" + projectName_Url + "/list/doc/query/"+ self.item.linkDocId,
                        method: "GET"
                    }).then(response => {
                        let _array = [];
                        if(response.content.info != null){
                            for(let i=0;i<response.content.info.length;i++){
                                _array.push({value:response.content.info[i].value,key:response.content.info[i].key});
                            }
                        }
                        self.$set("columnsReviseSet[6].options",_array)
                    }, error => {
                    });
                }
                //类型是商户时调用商户接口
                if(self.item.linkMchtId != '0'){
                    var mchtId = JSON.parse(localStorage.getItem("id_token")).mchtId
                    self.$post({
                        url: "/api/v2" + projectName_Url + "/list/mcht/"+ mchtId,
                        method:"GET"
                    }).then(response => {
                        let _array = [];
                        if(response.content.info != null){
                            for(let i=0;i<response.content.info.length;i++){
                                _array.push({value:response.content.info[i].value,key:response.content.info[i].key});
                            }
                        }
                        self.$set("columnsReviseSet[7].options",_array)
                    }, error => {
                    });
                }

                //监听类型
                linkTpeWatch()
                linkTpeWatch = self.$refs.item.$watch("item.linkType", function (v) {
                    if (v == 'normal' || v == 'mcht') {
                        self.columnsReviseSet.find(data => data.data == "linkUrl").readonly = true;
                        self.columnsReviseSet.find(data => data.data == "linkDocId").readonly = true;
                        $("input[name='linkUrl']").val("");
                        $("select[name='linkDocId']").val("");
                    } else if(v == 'url' || v == 'inner'){
                        self.columnsReviseSet.find(data => data.data == "linkUrl").readonly = false;
                        self.columnsReviseSet.find(data => data.data == "linkDocId").readonly = true;
                        $("input[name='linkUrl']").val(self.item.linkUrl);
                        $("select[name='linkDocId']").val("");
                    }else if(v == 'find'){
                        self.columnsReviseSet.find(data => data.data == "linkUrl").readonly = true;
                        self.columnsReviseSet.find(data => data.data == "linkDocId").readonly = false;
                        $("input[name='linkUrl']").val("");
                    }
                    if(v != 'mcht'){
                       self.columnsReviseSet.find(data => data.data == "linkMchtId").readonly = true;
                        $("select[name='linkMchtId']").val("");
                    }else{
                        self.columnsReviseSet.find(data => data.data == "linkMchtId").readonly = false;
                        $("select[name='linkMchtId']").val(self.item.linkMchtId);
                    }
                    if(v == 'mcht'){
                        var mchtId = JSON.parse(localStorage.getItem("id_token")).mchtId
                        self.$post({
                            url: "/api/v2" + projectName_Url + "/list/mcht/"+ mchtId,
                            method:"GET"
                        }).then(response => {
                            let _array = [];
                            if(response.content.info != null){
                                for(let i=0;i<response.content.info.length;i++){
                                    _array.push({value:response.content.info[i].value,key:response.content.info[i].key});
                                }
                            }
                            self.$set("columnsReviseSet[7].options",_array)
                        }, error => {
                        });
                    }
                    //验证关联链接
                    if(v == 'url'){
                        $(self.$els.reviseMform.linkUrl).rules("add", {
                            url:true
                        });
                    }else{
                        $(self.$els.reviseMform.linkUrl).rules("remove", "url");
                    }
                    $(self.$els.reviseMform).valid();
                });

                //编辑框验证、保存、提交
                $(self.$els.reviseMform).validate(self.item.valdate = {
                    async submitHandler() {
                        var form = self.$els.reviseMform;
                        let formData = new FormData(self.$els.reviseMform)
                        formData.set('state',dataArray.state)
                        // return flase
                        var result = await self.$post({
                            url: "/api/v1" + projectName_Url + "/plat/banner/update/" + self.item.banId,
                            data: formData,
                            method: "post"
                        });
                        Midway.alert({title: "操作提示", content: result.errorInfo})

                        dataTable.ajax.reload(null, false);
                        $(self.$els.reviseModal).modal('hide');
                        self.resetBindDrag()
                    },
                    errorPlacement: function (error, element) {
                        if (element.attr("name") == "file") {
                            error.insertAfter(".file-item");
                        } else {
                            error.insertAfter(element)
                        }
                    },
                    rules: {
                        banId: {
                            required: true,
                            readonly: true
                        },
                        name: {
                            required: true,
                            maxlength:25
                        },
                        about: {
                            maxlength:75
                        },
                        seq: {
                            digits: true,
                            required: true,
                            min: 1,
                            maxlength: 3,
                            minlength: 1
                        },
                        linkType: {
                            required: true
                        },
                        linkUrl: {
                            maxlength:122,
                            url: true
                        }
                    },
                    messages: {
                        linkUrl: {
                            url: "请输入以http://开始的正确网址"
                        }
                    }
                });
                $(self.$els.reviseModal).modal('show');
            });

            $(self.$el).on("click", ".delete", async function () {
                var Row = $(this).closest('tr').get(0);
                var name = dataTable.row(Row).data().name;
                var id = dataTable.row(Row).data().banId;

                await Midway.confirm({
                    title: "删除广告",
                    content: "是否要删除广告:" + name + "?"
                })
                var result = await self.$post({
                    url: "/api/v1" + projectName_Url + "/plat/banner/" + id,
                    data: {
                        banId: id
                    },
                    method: "DELETE"
                });
                Midway.alert({title: "操作提示", content: result.errorInfo})
                dataTable.ajax.reload();
            });

            $(self.$el).on("click", ".state", async function () {
                var Row = $(this).closest('tr').get(0);
                var value = dataTable.row(Row).data().name;
                var banId = dataTable.row(Row).data().banId;
                var seq = dataTable.row(Row).data().seq;
                var state = dataTable.row(Row).data().state == "0" ? "1" : "0";

                if (state == "1") {
                    await Midway.confirm({
                        title: "关闭广告",
                        content: "确认是否要关闭:" + value + "?"
                    })
                } else {
                    await Midway.confirm({
                        title: "开启广告",
                        content: "确认是否要开启:" + value + "?"
                    })
                }
                var _data = {banId: banId, state: state,seq:seq};
                var result = await self.$post({
                    url: "/api/v1" + projectName_Url + "/plat/banner/state",
                    data: _data,
                    method: "POST"
                });
                dataTable.ajax.reload();
            });
        },
        beforeDestroy() {
            $(this.$el).off("click")
        }
    }
</script>
